package com.hotelManager.www.servlet;

import com.hotelManager.www.controller.AuthController;
import com.hotelManager.www.po.User;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.common.Result;
import com.hotelManager.www.common.ResultCode;
import com.google.gson.Gson;
import com.hotelManager.www.config.GsonConfig;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.util.UUID;

/**
 * 统一认证Servlet
 * 处理所有用户的登录、注册和注销功能
 */
@WebServlet("/auth/*")
public class AuthServlet extends HttpServlet {
    private final AuthController authController = new AuthController();
    private final Gson gson = GsonConfig.getGson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write("{\"message\": \"GET 方法不被支持，请使用 POST 方法\"}");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        switch (pathInfo) {
            case "/login":
                handleLogin(request, response);
                break;
            case "/register":
                handleRegister(request, response);
                break;
            case "/logout":
                handleLogout(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    /**
     * 处理用户登录请求
     */
    private void handleLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 读取JSON数据
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        // 先解析出data字段（前端传递格式：{"data": "base64编码后的json字符串"}）
        JsonObject base64Obj = gson.fromJson(buffer.toString(), JsonObject.class);
        String base64Data = base64Obj.get("data").getAsString();
        // base64解码
        byte[] decodedBytes = java.util.Base64.getDecoder().decode(base64Data);
        String jsonStr = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);
        // 再解析为json对象
        JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
        String username = jsonObject.get("username").getAsString();
        String password = jsonObject.get("password").getAsString();
        String role = jsonObject.get("role").getAsString();

        // 验证参数
        if (username == null || password == null || role == null ||
                username.trim().isEmpty() || password.trim().isEmpty() || role.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "用户名、密码和角色不能为空")));
            return;
        }
        // 调用控制器进行登录
        User user = authController.login(username, password);

        if (user != null) {
            // 登录成功，将用户信息存入session
            HttpSession session = req.getSession();
            session.setAttribute("user", user);

            // 生成token
            String token = UUID.randomUUID().toString();
            session.setAttribute("token", token);
            System.out.println("生成的token: " + token);

            // 构造返回对象
            java.util.Map<String, Object> data = new java.util.HashMap<>();
            data.put("token", token);
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("password", user.getPassword());
            data.put("role", user.getRole());
            data.put("balance", user.getBalance());
            data.put("rechargeAmount", user.getRechargeAmount());
            data.put("rechargeStatus", user.getRechargeStatus());
            // ...如有其他字段可补充...

            // 根据用户角色返回不同的成功信息
            String message = "登录成功";
            if ("admin".equals(user.getRole())) {
                message = "管理员登录成功";
            } else if ("merchant".equals(user.getRole())) {
                message = "商户登录成功";
            } else if ("customer".equals(user.getRole())) {
                message = "客户登录成功";
            }

            resp.getWriter().write(gson.toJson(Result.success(data, message)));
        } else {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户名或密码错误")));
        }
    }
    /**
     * 处理用户注册求
     */
    private void handleRegister(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 读取JSON数据
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        // 解析JSON数据
        JsonObject jsonObject = gson.fromJson(buffer.toString(), JsonObject.class);

        // 获取注册信息
        String username = jsonObject.get("username").getAsString();
        String password = jsonObject.get("password").getAsString();
        String role = jsonObject.get("role").getAsString();

        // 验证参数
        if (username == null || password == null || role == null ||
                username.trim().isEmpty() || password.trim().isEmpty() || role.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "用户名、密码和角色不能为空")));
            return;
        }

        // 验证角色
        if (!"merchant".equals(role) && !"customer".equals(role)) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "角色只能是merchant或customer")));
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        user.setBalance(new java.math.BigDecimal("0.00"));
        user.setRechargeStatus("approved");
        user.setRechargeAmount(new java.math.BigDecimal("0.00"));

        boolean success;
        String message;

        if ("merchant".equals(role)) {
            // 商家注册只注册账号
            success = authController.registerMerchantUser(user);
            message = success ? "商户账号注册成功，请登录后完善店铺信息" : "商户账号注册失败";
        } else {
            // 普通用户注册
            success = authController.registerUser(user);
            message = success ? "用户注册成功" : "用户注册失败";
        }

        if (success) {
            resp.getWriter().write(gson.toJson(Result.success(message)));
        } else {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, message)));
        }
    }

    /**
     * 处理用户注销请求
     */
    private void handleLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        resp.getWriter().write(gson.toJson(Result.success("注销成功")));
    }
} 

